<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入名称" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="属性组" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="groupId">
              <j-search-select-tag v-model="model.groupId" dict="mdm_material_prop_group where enable_flag='1',name,id"  @change="groupIdChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sort">
              <a-input-number v-model="model.sort" placeholder="请输入排序" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea v-model="model.remark" rows="1" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="启用标志" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enableFlag">
              <j-switch v-model="model.enableFlag" :options="[1,0]" ></j-switch>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="属性值" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="mdmMaterialPropValueTable.loading"
          :columns="mdmMaterialPropValueTable.columns"
          :dataSource="mdmMaterialPropValueTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          @added="detailAdded"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'MdmMaterialPropForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
            enableFlag:"1",
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           name: [
              { required: true, message: '请输入名称!'},
           ],
          groupId: [
            { required: true, message: '请输入属性组!'},
          ],
        },
        refKeys: ['mdmMaterialPropValue', ],
        tableKeys:['mdmMaterialPropValue', ],
        activeKey: 'mdmMaterialPropValue',
        // 物料属性值
        mdmMaterialPropValueTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '编码',
              key: 'code',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '名称',
              key: 'name',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '排序',
              key: 'sort',
              type: FormTypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '启用标志',
              key: 'enableFlag',
              type: FormTypes.checkbox,
              customValue: [1,0],
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:"1",
            },
          ]
        },
        url: {
          add: "/mdm/materialProp/add",
          edit: "/mdm/materialProp/edit",
          queryById: "/mdm/materialProp/queryById",
          queryLatestSort: "/mdm/materialProp/queryLatestSortByGroupId",
          mdmMaterialPropValue: {
            list: '/mdm/materialProp/queryMdmMaterialPropValueByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      detailAdded(obj){
        this.autoSort(obj.row.id);
      },
      // 自动生成排序号
      autoSort(rowId){
        let editTable = this.$refs[this.refKeys[0]];
        let rows = editTable.rows;
        let num = 10;
        if(rows.length > 1){
          let lastId = editTable.getCleanId(rows[rows.length-2].id)
          let {values} = editTable.getValuesSync({ validate: false, rowIds: [lastId] });
          num = Number(values[0].sort) + 10
        }
        editTable.setValues([{rowKey: rowId, values:{sort: num}}])
      },
      groupIdChange(val){
        const that = this;
        if(val){
          getAction(this.url.queryLatestSort,{groupId: val}).then(res =>{
            if(res.success){
              this.$set(that.model, 'sort', res.result ? res.result + 10 : 10);
            }
          })
        }
      },
      addBefore(){
        this.mdmMaterialPropValueTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.mdmMaterialPropValue.list, params, this.mdmMaterialPropValueTable)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          mdmMaterialPropValueList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },

    }
  }
</script>

<style scoped>
</style>